package com.factors.DaiGuiCheng.aveStudyTime;

import org.apache.hadoop.io.DoubleWritable;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;

import java.io.IOException;

public class AveStudyTimeReducer extends Reducer<Text, IntWritable,Text, DoubleWritable> {
    private int totalSum = 0;
    private int totalCount = 0;

    @Override
    protected void reduce(Text key, Iterable<IntWritable> values, Context context)
            throws IOException, InterruptedException {
        for (IntWritable value : values) {
            totalSum += value.get();
            totalCount++;
        }
    }

    @Override
    protected void cleanup(Context context) throws IOException, InterruptedException {
        if (totalCount > 0) {
            double average = (double) totalSum / totalCount;

            context.write(new Text("平均成绩："), new DoubleWritable(average));
        } else {
            context.write(new Text("平均成绩："), new DoubleWritable(0.0));
        }
    }
}
